package com.example.auth.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import jakarta.annotation.PostConstruct;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * File storage configuration class, responsible for initializing upload directories
 */
@Configuration
public class FileStorageConfig {
    
    private static final Logger logger = LoggerFactory.getLogger(FileStorageConfig.class);
    
    @Value("${app.upload.dir:uploads}")
    private String uploadDir;
    
    /**
     * Initialize upload directory structure
     */
    @PostConstruct
    public void initUploadDirectories() {
        logger.info("Initializing file upload directory: {}", uploadDir);
        
        // Ensure base upload directory exists
        Path baseUploadPath = Paths.get(uploadDir).toAbsolutePath().normalize();
        if (!Files.exists(baseUploadPath)) {
            try {
                Files.createDirectories(baseUploadPath);
                logger.info("Created base upload directory: {}", baseUploadPath);
            } catch (Exception e) {
                logger.error("Failed to create upload directory: {}", e.getMessage());
            }
        }
        
        // Create task submission directory
        Path taskSubmissionsDir = baseUploadPath.resolve("task_submissions");
        if (!Files.exists(taskSubmissionsDir)) {
            try {
                Files.createDirectories(taskSubmissionsDir);
                logger.info("Created task submissions directory: {}", taskSubmissionsDir);
            } catch (Exception e) {
                logger.error("Failed to create task submissions directory: {}", e.getMessage());
            }
        }
    }
    
    /**
     * Ensure task directory exists, create if not
     * @param taskId Task ID
     * @return Task directory path
     */
    public Path ensureTaskDirectory(Long taskId) {
        Path baseUploadPath = Paths.get(uploadDir).toAbsolutePath().normalize();
        Path taskSubmissionsDir = baseUploadPath.resolve("task_submissions");
        Path taskDir = taskSubmissionsDir.resolve("task_" + taskId);
        
        if (!Files.exists(taskDir)) {
            try {
                Files.createDirectories(taskDir);
                logger.info("Created directory for task {}: {}", taskId, taskDir);
            } catch (Exception e) {
                logger.error("Failed to create directory for task {}: {}", taskId, e.getMessage());
            }
        }
        
        return taskDir;
    }
} 